package com.nami.gate.process.upmsg;


import com.nami.gate.config.RpcConfig;
import com.nami.gate.constants.ChannelConstants;
import com.nami.gate.middleware.mq.MqSender;
import com.nami.im.network.model.enums.protocol.CMDEnum;
import com.nami.im.network.model.packet.v2.Packet;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PingProcess implements PacketProcessor {

    private static final Logger log = LoggerFactory.getLogger(PingProcess.class);

    private MqSender mqSender;
    private RpcConfig rpcConfig;

    public PingProcess(MqSender mqSender, RpcConfig rpcConfig) {
        this.mqSender = mqSender;
        this.rpcConfig = rpcConfig;
    }

    @Override
    public void process(Channel channel, Packet packet) throws Exception {
        try {
            String userId = (String) channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).get();
            // 刷新ping 时间
            channel.attr(AttributeKey.valueOf(ChannelConstants.READ_TIME)).set(System.currentTimeMillis());
            channel.writeAndFlush(newPacket());
            log.info("[pong] 用户【userId={}】。通道【{}】交互正常", userId, channel.remoteAddress());
        } catch (Exception ex) {
            ex.printStackTrace();
        } // end try catch
    } //end process function

    private static @NotNull Packet newPacket() {
        Packet protocolPkt = new Packet();
        protocolPkt.setMagic((byte) 8);
        protocolPkt.setCmd(CMDEnum.PINGRESP.getCode());
        protocolPkt.setVersion((byte) 1);
        protocolPkt.setQos((byte) 0);
//        resp.setSerial((byte) 0);
//        resp.setEncrypt((byte) 0);
//        resp.setBody("".getBytes(StandardCharsets.UTF_8));
        protocolPkt.setBody(new byte[0]);
        return protocolPkt;
    }

}
